<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="书籍名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入书籍名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成书年份" prop="createTime">
        <el-input
          v-model="queryParams.createTime"
          placeholder="请输入成书年份"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="书籍类型" prop="bookType">
        <el-input
          v-model="queryParams.bookType"
          placeholder="请输入书籍类型"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- =========================================== -->
    <el-row :gutter="10" style="margin-bottom: 20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >我的书架</el-button
        >
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <!-- 表格数据 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="loading"
      border
      style="margin-bottom: 20px"
      :default-sort="{ prop: 'date', order: 'descending' }"
    >
      <el-table-column
        label="书名"
        prop="name"
        align="center"
      ></el-table-column>
      <el-table-column
        label="作者"
        prop="author"
        align="center"
      ></el-table-column>
      <el-table-column
        label="书籍种类"
        prop="bookType"
        align="center"
      ></el-table-column>
      <el-table-column
        label="出版组织"
        prop="publisher"
        align="center"
      ></el-table-column>
      <el-table-column
        label="成书年份"
        prop="createTime"
        align="center"
        sortable
      ></el-table-column>
      <!-- <el-table-column label="简介" prop="introduction" align="center"></el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleUpdate(scope.row)"
            v-permission="['SYSTEM', 'ADMIN']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            v-permission="['SYSTEM', 'ADMIN']"
            >删除</el-button
          >
          <el-button size="mini" @click="handleView(scope.row)"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageCurrent"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next"
      :total="total"
    ></el-pagination>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="书名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="书籍类型" prop="bookType">
          <el-input v-model="form.bookType" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" />
        </el-form-item>
        <el-form-item label="成书年份" prop="createTime">
          <el-input v-model="form.createTime" />
        </el-form-item>
        <el-form-item label="书籍简介" prop="introduction">
          <el-input v-model="form.introduction" />
        </el-form-item>
        <el-form-item label="上传书籍" prop="link">
          <el-upload
            :multiple="false"
            :show-file-list="false"
            action="#"
            :auto-upload="true"
            :http-request="uploadBooks"
          >
            <el-button size="small" type="primary" v-if="form.link == undefined"
              >点击上传</el-button
            >
            <el-button size="small" type="info" v-if="form.link != undefined"
              >已经上传</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="所需权限" prop="dataScope">
          <el-select v-model="form.dataScope">
            <el-option label="游客" value="0"></el-option>
            <el-option label="普通用户" value="1"></el-option>
            <el-option label="超级管理员" value="2"></el-option>
            <el-option label="系统管理员" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </div>
    </el-dialog>
    <!-- 预览书籍 -->
    <el-dialog
      title="查看详情"
      :visible.sync="viewVisible"
      width="600px"
      append-to-body
    >
      <h2>书名：{{ viewForm.name }}</h2>
      <el-button
        v-if="isLike == '0'"
        @click="like"
        type="warning"
        icon="el-icon-star-off"
        circle
        size="mini"
      ></el-button>
      <el-button
        v-if="isLike == '1'"
        @click="disLike"
        type="danger"
        icon="el-icon-star-off"
        circle
        size="mini"
      ></el-button>
      <p>简介：{{ viewForm.introduction }}</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadBookOne">下载</el-button>
        <el-button @click="pdfPreview">预览</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectBook,
  deleteBook,
  saveBook,
  uploadBook,
  updateBook,
  downloadBook,
  bookshelf,
  isLike,
  dislikeBook,
  likeBook,
} from "@/api/book";
import axios from "axios";
import { download } from "@/utils/download";
export default {
  data() {
    return {
      tableData: [],
      loading: false,
      // 表格条数
      total: undefined,
      queryParams: {
        pageCurrent: 1,
        pageSize: 10,
        name: undefined,
        author: undefined,
        bookType: undefined,
        createTime: undefined,
        bookType: undefined,
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {
        file: [],
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: "请输入书籍名", trigger: "blur" }],
        author: [{ required: true, message: "请输入作者", trigger: "blur" }],
        bookType: [
          { required: true, message: "请输入书籍类型", trigger: "blur" },
        ],
        publisher: [
          { required: true, message: "请输入出版社", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "请输入成书年份", trigger: "blur" },
        ],
        introduction: [
          { required: true, message: "请输入书籍简介", trigger: "blur" },
        ],
        dataScope: [{ required: true, message: "请选择权限" }],
        link: [{ required: true, message: "请上传书籍" }],
      },
      id: "",
      viewVisible: false,
      viewForm: {},
      pdfUrl: "",
      iframe: false,
      isLike: "",
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    // 获取表格数据
    getList() {
      this.loading = true;
      selectBook(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.loading = false;
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    // 分页==========================================================
    handleSizeChange(pageSizeVal) {
      this.queryParams.pageSize = pageSizeVal;
      this.getList();
    },
    handleCurrentChange(pageCurrentVal) {
      this.queryParams.pageCurrent = pageCurrentVal;
      this.getList();
    },
    // 清空表单
    restForm() {
      this.form = {
        name: undefined,
        author: undefined,
        bookType: undefined,
        introduction: undefined,
        dataScope: undefined,
        createTime: undefined,
        publisher: undefined,
        link: undefined,
      };
    },
    // 新增
    handleAdd() {
      this.restForm();
      this.id = "";
      this.open = true;
      this.title = "添加";
    },
    // 上传书籍
    // beforeUploadFile(file) {
    //   let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
    //   if (extension !== "pdf") {
    //     alert("文件格式不正确");
    //     return false;
    //   }
    // },
    uploadBooks(file) {
      let FormDatas = new FormData();
      FormDatas.append("file", file.file);
      uploadBook(FormDatas).then((res) => {
        if (res.code == 200) {
          console.log(res);
          this.form.link = res.data;
          this.$message.success(res.msg);
        }
      });
    },

    // 修改
    handleUpdate(row) {
      this.id = row.id;
      this.open = true;
      this.title = "编辑";
      this.form = JSON.parse(JSON.stringify(row));
    },

    // 表单提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.id == "") {
            saveBook(this.form)
              .then((res) => {
                if (res.code == 200) {
                  console.log(res);
                  this.open = false;
                  this.getList();
                  this.$message.success("添加成功");
                }
              })
              .catch(() => {
                this.open = false;
              });
          } else {
            updateBook(this.form)
              .then((res) => {
                if (res.code == 200) {
                  console.log(res);
                  this.open = false;
                  this.getList();
                  this.$message.success("更新成功");
                }
              })
              .catch(() => {
                this.open = false;
                return;
              });
          }
        }
      });
    },
    // 重置按钮
    resetForm() {
      this.restForm();
      this.$refs.form.resetFields();
    },
    // 删除
    async handleDelete(row) {
      const confirm = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      // 确定删除
      deleteBook({ bookId: row.id }).then((res) => {
        if (res.code !== 200) {
          this.$message.error("删除失败");
        } else {
          this.$message.success("删除成功");
          this.getList();
        }
      });
    },
    // 查看详情
    handleView(row) {
      this.viewVisible = true;
      this.viewForm = row;
      isLike({ bookId: row.id }).then((res) => {
        this.isLike = res.data.data;
      });
    },
    disLike() {
      dislikeBook({ bookId: this.viewForm.id }).then((res) => {
        if (res.code == 200) {
          this.isLike = 0;
        }
      });
    },
    like() {
      likeBook({ bookId: this.viewForm.id }).then((res) => {
        if (res.code == 200) {
          this.isLike = 1;
        }
      });
    },
    // 预览
    pdfPreview() {
      console.log(this.viewForm.link)
      downloadBook({ bookId: this.viewForm.id, openStyle: "inline" }).then(
        (res) => {
          this.$router.push({
            path: "/epub/index",
            query: {
              url: this.viewForm.link,
            },
          });
        }
      );
      // 之前的
      // downloadBook({ bookId: this.viewForm.id, openStyle: "inline" }).then(
      //   (res) => {
      //           window.open("http://" + this.viewForm.link, "_blank");

      //     const binaryData = [];
      //     binaryData.push(res);
      //     // 获取blob链接
      //     this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf;charset=UTF-8' }));
      //   }
      // );
    },
    // 下载
    downloadBookOne() {
      downloadBook({ bookId: this.viewForm.id, openStyle: "attachment" }).then(
        (res) => {
          window.open(
            "http://" + this.viewForm.link + "?openStyle=attachment",
            "_blank"
          );
          // let blob = new Blob([res], { type: 'application/pdf' });
          // let downloadElement = document.createElement("a");
          // let href = window.URL.createObjectURL(blob); //创建下载的链接
          // downloadElement.href = href;
          // downloadElement.download = `书籍-${this.name}`    //下载后的文件名，根据需求定义
          // document.body.appendChild(downloadElement);
          // downloadElement.click(); //点击下载
          // document.body.removeChild(downloadElement); //下载完成移除元素
          // window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      );
    },
    // 我的书架
    async handleExport() {
      let res = await bookshelf(this.queryParams);
      if (res.code == 200) {
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageCurrent = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.getList();
    },
    close() {
      this.$refs.form.resetFields();
      this.form = {
        name: undefined,
        author: undefined,
        bookType: undefined,
        introduction: undefined,
        dataScope: undefined,
        createTime: undefined,
        publisher: undefined,
        link: undefined,
      };
    },
  },
};
</script>
